<?php

namespace Crm\Model;

/**
 * 客户数据库模型
 *
 * @author SoChishun <14507247@qq.com>
 * @version 1.0
 * @since 1.0.0 <2015-4-1> SoChishun Added.
 */
class CustomerModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 'tuser_customer';

    /**
     * 字段定义
     * @var array
     */
    protected $fields = array('user_id', 'interested', 'contact_results', 'tags', 'level', 'buy_count', 'integral', 'cumulative_amount', 'last_buy_time', 'last_visit_time', 'referrer_user_id', 'agent_id', 'old_agent_id', 'ex_tags', '_pk' => 'id', '_autoinc' => true);

    /**
     * 命名范围
     * @var array
     */
    protected $_scope = array();

    /**
     * 是否批量验证
     * @var boolean
     */
    protected $patchValidate = true;

    /**
     * 验证规则
     * @var array
     */
    protected $_validate = array();

    /**
     * 自动填充
     * @var array
     */
    protected $_auto = array();

    public function import_from_excel($file_id) {
        $M = M('tcommon_file');
        $list = $M->field('filePath, fileExt')->find($fid);

        $path = UPLOAD_ROOT . $list['filePath'];
        if (!file_exists($path)) {
            $this->result(false, '文件路径不存在! [' . $path . ']', U('CtiTask/import_number'));
        }
        // 导入Excel
        vendor('PHPExcel.PHPExcel');
        $objPHPExcel = PHPExcel_IOFactory::load($path);
        $sheet = $objPHPExcel->getActiveSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数,数值,如:30
        $highestColumnName = $sheet->getHighestColumn(); // 取得总列数,字符,如:F
        $highestColumn = PHPExcel_Cell::columnIndexFromString($highestColumnName); // 转换成数值
        $count = $highestRow - 1;
        if ($tsid) {
            if (!$this->check_max_task_num($siteID, $tsid, $count)) {
                $M->execute('delete from tcti_task where id=' . $id);
                $this->result(false, '该任务策略中所有任务号码数量已超过您的最大任务数,请在该任务策略中删除部分任务后继续操作!', U('CtiTask/import_number'), 5);
            }
        }

        $arrVals = array();
        // $sql = 'insert into ' . $table . ' (taskID, trunkName, taskStrategyID, customerName, phoneNumber, sex, idNo, address, detailMsg, source, siteID) values ';
        // $tpl = "$id,'$trunkName',$tsid,'%s','%s','%s','import',$siteID";
        $tpl = sprintf('%d,"%s",%d,"%%s","%%s","%%s","%%s","%%s","%%s","import",%d', $id, $trunkName, $tsid, $siteID);
        for ($i = 2; $i <= $highestRow; $i++) {
            $num = $sheet->getCell("A" . $i)->getValue(); //第一列
            $num = trim($num);
            if (!$num) {
                continue;
            }
            $customer_name = $sheet->getCell("B" . $i)->getValue(); //第二列
            $customer_sex = $sheet->getCell("C" . $i)->getValue();
            $customer_id_no = $sheet->getCell("D" . $i)->getValue();
            $customer_address = $sheet->getCell("E" . $i)->getValue(); // 第五列
            $start = 5;
            $end = $highestColumn - $start;
            if ($start < $end) {
                $str = '';
                for ($i2 = $start; $i2 < $end; $i2++) {
                    $str .= sprintf('%s=%s|', $sheet->getCellByColumnAndRow($i2, 1)->getValue(), $sheet->getCellByColumnAndRow($i2, $i)->getValue());
                }
                $c = rtrim($str, ',');
            } else {
                $c = $sheet->getCell("F" . $i)->getValue(); //第六列
            }
            $arrVals[] = sprintf($tpl, $customer_name, $prefix . $num, $customer_sex, $customer_id_no, $customer_address, $c);
        }

        if (!$arrVals) {
            $this->result(false, '没有号码!', U('CtiTask/import_number'));
        }
        if ($rule == 'random') {
            shuffle($arrVals);
        }
        $dir = get_appdata_dir(array('siteID' => $this->loginData['siteID'], 'userID' => $this->loginData['id'], 'type' => 'tempsqls', 'subdir' => 'CustomerImp'));
        $path = $dir . date('Ymdhis') . '_';
        $count = count($arrVals);
        $n = 0;
        for ($i = 0; $i < $count; $i++) {
            if ($i % 3000 == 0) {
                $sql = implode(PHP_EOL, array_slice($arrVals, 0, 3000));
                file_put_contents($path . $n . '.sql', $sql);
                array_splice($arrVals, 0, 3000);
                $n++;
            }
        }
        if (count($arrVals) > 0) {
            $sql = implode(PHP_EOL, $arrVals);
            file_put_contents($path . $n . '.sql', $sql);
            $n++;
        }
        $M->execute('set names utf8;');
        for ($i = 0; $i < $n; $i++) {
            $filepath = $path . $i . '.sql';
            $filepath = sofunc_dir_format($filepath);
            $sql = "load data infile '$filepath' into table $table  character set utf8" . ' FIELDS TERMINATED BY "," ENCLOSED BY \'"\' ESCAPED BY "\\\" LINES TERMINATED BY "\n" STARTING BY "" (taskID, trunkName, taskStrategyID, customerName, phoneNumber, sex, idNo, address, detailMsg, source, siteID)';
            $M->execute($sql);
        }
        sleep(5);
        if ($skipDuplicate) {
            $dup = $M->execute("delete a from $table a INNER JOIN tcti_call_number$tsid b on a.phoneNumber=b.phoneNumber where a.taskID=$id;");
            if (false !== $dup) {
                $count = $count - $dup;
            }
        }
        $M->execute('insert into tcti_call_number' . $tsid . ' (taskID, trunkName, taskStrategyID, customerName, phoneNumber, sex, idNo, address, detailMsg, source, siteID) select taskID, trunkName, taskStrategyID, customerName, phoneNumber, sex, idNo, address, detailMsg, source, siteID from ' . $table . ' where taskID=' . $id);
        $M->execute('update tcti_task set telsCount=' . $count . ', unCallCount=' . $count . ' where id=' . $id);
        $M->execute('delete from ' . $table . ' where taskID=' . $id);
    }
    
    /**
     * 保存客户
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function save_item(){        
        
        
        // 扩展字段
        $list = sofunc_get_sys_exfield_list('CUSTOMER', $siteID);
        $exdata = $params->patchParams($list);
        if ($params->hasError()) {
            $this->act_error($params->getError());
        }
        $zipCode = I('zipCode');
        $params->addData('idNo');
        $params->addData('remark');
        $params->addData('address');
        $params->addData('interested');
        // $params->addData('contactResults');
        $params->addData('tags');

        if ($id) {
            $params->addData('id', $id);
            $result = $M->save($params->getParams());
            if (false !== $result) {
                $sqls = false;
                if ($exdata) {
                    $str = '';
                    foreach ($exdata as $k => $v) {
                        $str.=",`$k`='$v' ";
                    }
                    if ($str) {
                        $str = substr($str, 1);
                    }
                    $sqls = "update tcustomer_ex_$siteID set $str where userID=$id;";
                    $M->execute($sqls);
                }
            }
        } else {
            $params->addData('state', 1);
            $params->addData('createdTime', now());
            $result = $M->add($params->getParams());
            if (false !== $result) {
                $id = $result;
                $sqls = false;
                if ($exdata) {
                    $sqls[] = "insert into tcustomer_ex_$siteID (userID, " . implode(',', array_keys($exdata)) . ") values ($id, '" . implode("','", array_values($exdata)) . "');";
                }
                // 新增客户的时候自动保存地址
                $address = AddressAction::split_cnregion(I('address'));
                if ($address && ($address[0] || $address[3])) {
                    $sqls[] = "insert into tuser_address (userID, consignee, telphone, province, city, area, street, zipCode) values ($id, '$personalName', '$telphone', '" . $address[0] . "', '" . $address[1] . "', '" . $address[2] . "', '" . $address[3] . "', '$zipCode');";
                }
                if ($sqls) {
                    $M->patchQuery($sqls);
                }
            }
        }
        if ($result === false) {
            $this->act_error('保存失败');
        } else {
            if (C('APPCONF.CUSTOMER_EDIT_CLOSE_ON_SAVE')) {
                $this->act_close_dialog(true, '保存成功!');
            } else {
                $this->success('保存成功!', U('Customer/customer_edit', 'rp=1&id=' . $id));
            }
        }
    }

}
